package umage.figures;

import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.geom.Point2D;
import java.awt.geom.Point2D.Double;
import java.util.ArrayList;
import java.util.Collection;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JOptionPane;

import org.jhotdraw.draw.ArrowTip;
import org.jhotdraw.draw.AttributeKeys;
import org.jhotdraw.draw.Figure;
import org.jhotdraw.draw.LineConnectionFigure;
import org.jhotdraw.draw.ConnectionTool;

@FigureInfo(icon = "FlowArrow.png", name = "Flow Arrow", toolbar = "Arrows", toolbarPriority = 1, tool = ConnectionTool.class)
public class FlowArrow extends LineConnectionFigure {
	
	public FlowArrow() {
		setAttribute(AttributeKeys.END_DECORATION, new ArrowTip(0.35, 12, 0.5, true, true, true));
		setAttribute(AttributeKeys.TEXT, "1");
	}
	
	@Override
	public Collection<Action> getActions(Double p) {
		ArrayList<Action> actions = new ArrayList<Action>();
		actions.add(new ChangeCountAction());
		return actions;
	}
	
	@Override
	protected void drawText(Graphics2D g) {
		int pCount = getPointCount();
		Point2D.Double target;
		if (pCount % 2 == 0) { // even number of points
			target = getPoint((pCount / 2) - 1);
			Point2D.Double secondary = getPoint(pCount / 2);
			target.x = (target.x + secondary.x) / 2;
			target.y = (target.y + secondary.y) / 2; 
		} else { // odd number of points
			target = getPoint((pCount - 1) / 2);
		}
		g.drawString((String)getAttribute(AttributeKeys.TEXT), (int)target.x, (int)target.y);
	}
	
	@Override
	public boolean canConnect(Figure start, Figure end) {
		if (!super.canConnect(start, end)) return false;
		if (start instanceof PlaceFigure && end instanceof TransitionFigure) return true;
		else if (start instanceof TransitionFigure && end instanceof PlaceFigure) return true;
		return false;
	}
	
	protected class ChangeCountAction extends AbstractAction {
		
		public ChangeCountAction() {
			super("Change Value...");
		}
		
		@Override
		public void actionPerformed(ActionEvent arg0) {
			while (true) {
				String result = JOptionPane.showInputDialog(null, "New token value:", getAttribute(AttributeKeys.TEXT));
				if (result == null) break;
				try {
					Integer val = Integer.parseInt(result, 10);
					if (val > 0) {
						setAttribute(AttributeKeys.TEXT, val.toString());
						break;
					}
				} catch (Exception ex) {}
				JOptionPane.showMessageDialog(null, "Please enter a valid positive number", "Invalid Input", JOptionPane.ERROR_MESSAGE);
			}
		}
		
	}
	
	public int getTransferCount() {
		return Integer.parseInt((String)getAttribute(AttributeKeys.TEXT)); // should never be invalid short of corrupt save file
	}
	
}
